package tools
{
	import com.greensock.TweenMax;
	import com.greensock.easing.Bounce;
	import com.greensock.easing.Elastic;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.InteractiveObject;
	import flash.events.MouseEvent;

	/**
	 * 翻页组件 
	 * @author 青竹.
	 * 
	 */
	public class PageControler
	{
		private var _contain:DisplayObjectContainer;
		public var row:int=3;
		public var col:int=3;
		public var tileWith:Number=50;
		public var tileHeigh:Number=50;
		private var _currrentPos:int;
		private var initX:Number;
		private var _amount:int;
		private var _rightBt:InteractiveObject;
		private var _leftBt:InteractiveObject;
		public function PageControler(leftBt:InteractiveObject,rightBt:InteractiveObject,contain:DisplayObjectContainer)
		{
			_contain=contain;
			initX=_contain.x;
			_rightBt=rightBt;
			_leftBt=leftBt;
			
			leftBt.addEventListener(MouseEvent.CLICK,onLeft,false,0,true);
			rightBt.addEventListener(MouseEvent.CLICK,onRight,false,0,true);
		}
		public function removeAll():void{
			while(_contain.numChildren){
			   _contain.removeChildAt(0);
			}
			_currrentPos=0;
			_amount=0;
			_contain.x=initX;
		}
		public function atLastPage():void{
			var pd:int = Math.floor(_amount / (row*col));
			_currrentPos=pd;
			_contain.x=initX-_currrentPos*row*tileWith;
		}
		public function gotoPage(index:int):void{
			var ps:int = index % _amount;
			
			var pd:int=Math.floor(ps/(row*col));
			_currrentPos=pd;
			_contain.x=initX-_currrentPos*row*tileWith;
		}
		private function onLeft(e:MouseEvent):void{
			if(_currrentPos==0) return; 
			_currrentPos--;
			TweenMax.to(_contain,.5,{x:initX-_currrentPos*row*tileWith});
		}
		private var _page:int;
		private function onRight(e:MouseEvent):void{
			if(_currrentPos==Math.ceil(_amount/(row*col))-1) return; 
		   _currrentPos++;	  
		   TweenMax.to(_contain,.5,{x:initX-_currrentPos*row*tileWith});
		}
		public var isEffect:Boolean=false;
	    public function addChild(e:DisplayObject):void{
			 _page=Math.floor((_amount)/(row*col));
			 //if(_page<=1){}
			 _leftBt.visible = _rightBt.visible=_page>=1;
				 
			 var pos:Number = _page*row*tileWith; 
			 var pd:int = _amount % (row*col);
			 var px:Number=pos+tileWith*(pd % row);
			 var py:Number=tileHeigh*Math.floor(pd / row);
			if(isEffect){
				e.x=1000;
			    TweenMax.to(e,1,{x:px,ease:Bounce.easeOut});
			}else{
				e.x = px;
				
			}
			e.y = py;
			_contain.addChild(e);
			_amount++;		
	    }
	}
}